/*
 * Copyright (c) 2020-2021 imlzw@vip.qq.com jweb.cc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cc.jweb.adai.plugin.monitor;

import cc.jweb.adai.web.system.generator.service.WebServerService;
import cc.jweb.boot.utils.lang.StringUtils;
import com.jfinal.plugin.IPlugin;
import io.jboot.Jboot;

/**
 * 测试web专用的父进程监控程序
 */
public class TestWebMonitorPlugin implements IPlugin {
    Thread monitorParentJweb = null;

    @Override
    public boolean start() {
        String jwebPPid = Jboot.configValue("jweb.ppid");
        if (StringUtils.notBlank(jwebPPid)) {
            System.out.println("Jweb start test jweb ppid (" + jwebPPid + ") moniton program!");
            monitorParentJweb = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            Thread.sleep(1000 * 10);

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        if (!WebServerService.checkJwebPidExist(jwebPPid)) {
                            System.out.println("Jweb cant monitor jweb ppid (" + jwebPPid + "), JVM Exit!");
                            // 退出java虚拟机
                            System.exit(0);
                        }
                    }
                }
            });
            monitorParentJweb.start();
        }
        return true;
    }

    @Override
    public boolean stop() {
        if (monitorParentJweb != null) {
            monitorParentJweb.interrupt();
        }
        return true;
    }
}
